import { defineStore } from 'pinia'
import { userEmailLogin, userProfile } from '../api/user'
import { encrypted } from '../utils/jsencrypt';

export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: null as any | null,
        token: localStorage.getItem('token') || '',
        isLoading: false
    }),

    actions: {
        async loginByEmail(credentials: { email: string; password: string }) {
            this.isLoading = true
            credentials.password = encrypted(credentials.password)
            try {
                const res = await userEmailLogin(credentials)
                this.token = res.data.token
                localStorage.setItem('token', res.data.token)
                this.user = res.data.user
                return res.data
            } catch (e) {
                return e
            }
            finally {
                this.isLoading = false
            }
        },
        async fetchUserProfile() {
            this.isLoading = true
            try {
                const res = await userProfile()
                this.user = res.data
            } catch (error) {
                console.error('获取用户详情失败:', error)
            } finally {
                this.isLoading = false
            }
        },
        
    }
})